package com.cwvs.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
/**
 * JSON格式转换类
 * @author mickey
 *
 */
public class JsonUtil {
    private static Logger logger = Logger.getLogger(JsonUtil.class);

    static public String toJson(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        StringWriter sw = new StringWriter();
        try {
            mapper.writeValue(sw, object);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getStackTrace());
        }
        return sw.toString();
    }
    
    /**
     * JSON字符串解析成MAP
     * @param jsonString
     * @return
     */
    @SuppressWarnings({ "rawtypes" })
    static public Map parseJsonToMap(String jsonString) {
        ObjectMapper mapper = new ObjectMapper();
        Map<?, ?> map = null;
        try {
            map = mapper.readValue(jsonString, Map.class);
        } catch (JsonParseException e) {
           // e.printStackTrace();
        } catch (JsonMappingException e) {
            //e.printStackTrace();
        } catch (IOException e) {
            //e.printStackTrace();
        }
        return map;
    }
    
    /**
     * 解析json字符串为list
     * 
     * @param jsonString
     * @return
     * @throws IOException 
     * @throws JsonMappingException 
     * @throws JsonParseException 
     */
    @SuppressWarnings("rawtypes")
	public static List parseJsonToList(String jsonString) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<?> list = null;
            list = mapper.readValue(jsonString, List.class);
        return list;
    }

}
